<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script>
    class EventEmitter{
        constructor() {
            this.events = {}
        }
        on(eventName,listener){
            if (!this.events[eventName]) this.events[eventName] = []
            this.events[eventName].push(listener)
            return this
        }
        emit(eventName,...args){
            const listeners = this.events[eventName]
            if (!listeners) return this
            for(let listener of listeners){
                listener.apply(this,args)
            }
            return this
        }
        off(eventName,listener){
            const listeners = this.events[eventName]
            if (!listeners) return this
            this.events[eventName] = listeners.filter(i => i !== listener)
            return this
        }
        once(eventName,listener){
            const onceEvent = (...args) => {
                listener.apply(this,args)
                this.off(eventName,onceEvent)
            }
            this.on(eventName,onceEvent)
        }
    }

    const emitter = new EventEmitter();
    emitter.on('greet', (name) => {
        console.log(`Hello, ${name}!`);
    });

    emitter.once('farewell', (name) => {
        console.log(`Goodbye, ${name}!`);
    });
    emitter.emit('greet', 'Alice'); // 输出: Hello, Alice!
    emitter.emit('greet', 'Bob');   // 输出: Hello, Bob!

    emitter.emit('farewell', 'Charlie'); // 输出: Goodbye, Charlie!
    emitter.emit('farewell', 'David');   // 无输出（监听器已移除）
    const greetListener = (name) => {
        console.log(`Hi, ${name}!`);
    };

    emitter.on('greet', greetListener);
    emitter.emit('greet', 'Eve'); // 输出: Hi, Eve!

    emitter.off('greet', greetListener);
    emitter.emit('greet', 'Frank'); // 无输出（监听器已移除）
</script>
</html>